package service;

import org.springframework.stereotype.Service;
import pojo.Exercise;
import pojo.ExerciseResult;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service

public class ExerciseServiceImpl implements ExerciseService {
    // 随机数生成器
    private static final Random random = new Random();
    // 运算符
    private static final String[] OPERATORS = {"+", "-", "*", "/"};
    // 文件位置
    private static final String HISTORY_DIR = "data/history/";

    @Override
    public List<Exercise> generateExercises(int count) {
        List<Exercise> problems = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            Exercise problem = generateSingleExercise();
            problems.add(problem);
        }
        return problems;
    }

    @Override
    public Exercise generateSingleExercise() {
        int num1 = random.nextInt(100) + 1; // 1-100
        int num2 = random.nextInt(100) + 1;
        String operator = OPERATORS[random.nextInt(OPERATORS.length)];
        int correctAnswer = 0;
        String question = "";

        switch (operator) {
            case "+":
                correctAnswer = num1 + num2;
                question = num1 + "+" + num2 + "=";
                break;
            case "-":
                // 确保结果非负：交换num1和num2
                if (num1 < num2) {
                    int temp = num1;
                    num1 = num2;
                    num2 = temp;
                }
                correctAnswer = num1 - num2;
                question = num1 + "-" + num2 + "=";
                break;
            case "*":
                correctAnswer = num1 * num2;
                question = num1 + "*" + num2 + "=";
                break;
            case "/":
                // 确保整除：num1 = num2 * 商（商为1-10）
                int quotient = random.nextInt(10) + 1;
                num1 = num2 * quotient;
                correctAnswer = quotient;
                question = num1 + "/" + num2 + "=";
                break;
            default:
                throw new RuntimeException("无效运算符");
        }
        return new Exercise(question, correctAnswer);
    }

    @Override
    public ExerciseResult checkAnswers(List<Exercise> problems, List<Integer> userAnswers) {
        int total = problems.size();
        int correctCount = 0;

        // 匹配用户答案与题目，判断对错
        for (int i = 0; i < total; i++) {
            Exercise problem = problems.get(i);
            int userAnswer = userAnswers.get(i);
            problem.setUserAnswer(userAnswer);
            problem.setCorrect(problem.getCorrectAnswer() == userAnswer);
            if (problem.isCorrect()) {
                correctCount++;
            }
        }
        // 计算正确率
        double accuracy = (double) correctCount / total * 100;
        return new ExerciseResult(problems, total, correctCount, accuracy, getCurrentTimestamp());
    }

    // 获取当前时间戳（yyyyMMddHHmmss）
    private String getCurrentTimestamp() {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    }

    @Override
    public void saveResult(ExerciseResult result) {
        // 确保历史目录存在
        File dir = new File(HISTORY_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 文件名：student_yyyyMMdd.csv（假设当前用户为student，实际需从登录信息获取）
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String filename = HISTORY_DIR + "student_" + date + ".csv";
        File file = new File(filename);

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, true))) {
            // 若文件为空，先写表头
            if (file.length() == 0) {
                writer.write("timestamp,question,correct_answer,user_answer,is_correct");
                writer.newLine();
            }

            // 写入每道题的记录
            for (Exercise problem : result.getProblems()) {
                String line = String.join(",",
                        result.getTimestamp(),
                        problem.getQuestion(),
                        String.valueOf(problem.getCorrectAnswer()),
                        String.valueOf(problem.getUserAnswer()),
                        String.valueOf(problem.isCorrect())
                );
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            throw new RuntimeException("保存历史记录失败", e);
        }
    }

    @Override
    public List<String> getHistory() {
        List<String> history = new ArrayList<>();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String filename = HISTORY_DIR + "student_" + date + ".csv";
        File file = new File(filename);

        if (file.exists()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    history.add(line);
                }
            } catch (IOException e) {
                throw new RuntimeException("读取历史记录失败", e);
            }
        }
        return history;
    }
}
